package com.lanou.bbs.controller;

import com.lanou.bbs.entity.User;
import com.lanou.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.jvm.hotspot.debugger.posix.elf.ELFSectionHeader;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    @RequestMapping("/login")
    public String login(User user, HttpSession session, Model model) throws SQLException {
        //1.接收请求参数
        //2.调用service 获取登录结果
        User u = userService.login(user);
        //3.判断登录结果
        if (u != null) {
            //3.1登录成功
            //3.1.1 将登陆成功的user存session中,以保证登录状态
            session.setAttribute("user", u);
            //3.1.2 跳转到主页
            return "redirect:/index.jsp";
        } else {
            //3.2登录失败
            //3.2.1 request中存失败信息
            model.addAttribute("msg", "用户名货或密码错误");
            model.addAttribute("user", user);
            //3.2.2 跳转到登录页面
            return "login";
        }
    }
    @RequestMapping("/register")
    public String register(User user,Model model){
        boolean rs= userService.register(user);
        if (rs){
            return "redirect:/index.jsp";
        }else {
            model.addAttribute("msg","注册失败");
            return "register";
        }
    }
}

